package com.zliblike_platform.service.impl;

import com.zliblike_platform.dto.CommentDTO;
import com.zliblike_platform.entity.Comment;
import com.zliblike_platform.entity.CommentLike;
import com.zliblike_platform.entity.User;
import com.zliblike_platform.mapper.CommentLikeMapper;
import com.zliblike_platform.mapper.CommentMapper;
import com.zliblike_platform.mapper.UserMapper;
import com.zliblike_platform.service.CommentService;
import com.zliblike_platform.vo.CommentVO;
import com.zliblike_platform.vo.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 评论服务实现类
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    
    @Autowired
    private CommentLikeMapper commentLikeMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    @Transactional
    public Long addBookComment(Long userId, Long bookId, CommentDTO commentDTO) {
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setBookId(bookId);
        comment.setContent(commentDTO.getContent());
        comment.setLikes(0);
        comment.setCreatedAt(LocalDateTime.now());
        comment.setParentCommentId(commentDTO.getParentCommentId());
        
        commentMapper.insert(comment);
        return comment.getCommentId();
    }
    
    @Override
    @Transactional
    public Long addListComment(Long userId, Long listId, CommentDTO commentDTO) {
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setListId(listId);
        comment.setContent(commentDTO.getContent());
        comment.setLikes(0);
        comment.setCreatedAt(LocalDateTime.now());
        comment.setParentCommentId(commentDTO.getParentCommentId());
        
        commentMapper.insert(comment);
        return comment.getCommentId();
    }
    
    @Override
    @Transactional
    public boolean deleteComment(Long userId, Long commentId) {
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null || !comment.getUserId().equals(userId)) {
            return false;
        }
        
        return commentMapper.deleteById(commentId) > 0;
    }
    
    @Override
    @Transactional
    public int likeComment(Long userId, Long commentId) {
        // 检查是否已点赞
        CommentLike existingLike = commentLikeMapper.selectByCommentIdAndUserId(commentId, userId);
        if (existingLike != null) {
            // 已点赞，不重复处理
            Comment comment = commentMapper.selectById(commentId);
            return comment != null ? comment.getLikes() : 0;
        }
        
        // 新增点赞记录
        CommentLike commentLike = new CommentLike();
        commentLike.setCommentId(commentId);
        commentLike.setUserId(userId);
        commentLike.setCreatedAt(LocalDateTime.now());
        commentLikeMapper.insert(commentLike);
        
        // 更新评论点赞数
        commentMapper.incrementLikes(commentId);
        
        // 返回更新后的点赞数
        Comment comment = commentMapper.selectById(commentId);
        return comment != null ? comment.getLikes() : 0;
    }
    
    @Override
    @Transactional
    public int unlikeComment(Long userId, Long commentId) {
        // 检查是否已点赞
        CommentLike existingLike = commentLikeMapper.selectByCommentIdAndUserId(commentId, userId);
        if (existingLike == null) {
            // 未点赞，不需要处理
            Comment comment = commentMapper.selectById(commentId);
            return comment != null ? comment.getLikes() : 0;
        }
        
        // 删除点赞记录
        commentLikeMapper.delete(commentId, userId);
        
        // 更新评论点赞数
        commentMapper.decrementLikes(commentId);
        
        // 返回更新后的点赞数
        Comment comment = commentMapper.selectById(commentId);
        return comment != null ? comment.getLikes() : 0;
    }
    
    @Override
    public PageResult<CommentVO> getBookComments(Long bookId, Long userId, int page, int size) {
        // 计算总数
        Integer total = commentMapper.countByBookId(bookId);
        PageResult<CommentVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setCurrentPage(page);
        int totalPages = (total + size - 1) / size;
        pageResult.setTotalPages(totalPages);
        
        // 没有数据直接返回
        if (total == 0) {
            pageResult.setRecords(new ArrayList<>());
            return pageResult;
        }
        
        // 查询父评论列表
        int offset = (page - 1) * size;
        List<Comment> comments = commentMapper.selectByBookId(bookId, offset, size);
        
        // 转换为VO对象
        List<CommentVO> commentVOs = convertToCommentVOList(comments, userId);
        
        pageResult.setRecords(commentVOs);
        return pageResult;
    }
    
    @Override
    public PageResult<CommentVO> getListComments(Long listId, Long userId, int page, int size) {
        // 计算总数
        int total = commentMapper.countByListId(listId);
        PageResult<CommentVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setCurrentPage(page);
        int totalPages = (total + size - 1) / size;
        pageResult.setTotalPages(totalPages);
        
        // 没有数据直接返回
        if (total == 0) {
            pageResult.setRecords(new ArrayList<>());
            return pageResult;
        }
        
        // 查询父评论列表
        int offset = (page - 1) * size;
        List<Comment> comments = commentMapper.selectByListId(listId, offset, size);
        
        // 转换为VO对象
        List<CommentVO> commentVOs = convertToCommentVOList(comments, userId);
        
        pageResult.setRecords(commentVOs);
        return pageResult;
    }
    
    /**
     * 将评论列表转换为VO对象列表
     * @param comments 评论列表
     * @param userId 当前用户ID
     * @return VO对象列表
     */
    private List<CommentVO> convertToCommentVOList(List<Comment> comments, Long userId) {
        if (comments == null || comments.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取评论用户信息
        List<Long> userIds = comments.stream()
                .map(Comment::getUserId)
                .distinct()
                .collect(Collectors.toList());
        
        Map<Long, User> userMap = new HashMap<>();
        for (Long id : userIds) {
            User user = userMapper.selectById(id);
            if (user != null) {
                userMap.put(id, user);
            }
        }
        
        // 获取评论ID列表
        List<Long> commentIds = comments.stream()
                .map(Comment::getCommentId)
                .collect(Collectors.toList());
        
        // 查询用户是否点赞
        List<Long> likedCommentIds = new ArrayList<>();
        if (userId != null) {
            likedCommentIds = commentLikeMapper.selectLikedCommentIds(commentIds, userId);
        }
        
        // 查询所有回复
        Map<Long, List<Comment>> repliesMap = new HashMap<>();
        for (Long commentId : commentIds) {
            List<Comment> replies = commentMapper.selectReplies(commentId);
            if (replies != null && !replies.isEmpty()) {
                repliesMap.put(commentId, replies);
                
                // 添加回复用户ID
                List<Long> replyUserIds = replies.stream()
                        .map(Comment::getUserId)
                        .distinct()
                        .collect(Collectors.toList());
                
                for (Long id : replyUserIds) {
                    if (!userMap.containsKey(id)) {
                        User user = userMapper.selectById(id);
                        if (user != null) {
                            userMap.put(id, user);
                        }
                    }
                }
                
                // 添加回复评论ID
                List<Long> replyCommentIds = replies.stream()
                        .map(Comment::getCommentId)
                        .collect(Collectors.toList());
                
                commentIds.addAll(replyCommentIds);
            }
        }
        
        // 如果有新增的评论ID，需要再次查询点赞状态
        if (commentIds.size() > comments.size() && userId != null) {
            likedCommentIds = commentLikeMapper.selectLikedCommentIds(commentIds, userId);
        }
        
        // 转换评论对象
        List<CommentVO> result = new ArrayList<>();
        for (Comment comment : comments) {
            CommentVO vo = convertToCommentVO(comment, userMap, likedCommentIds);
            
            // 添加回复列表
            if (repliesMap.containsKey(comment.getCommentId())) {
                List<Long> likedCommentIdss = likedCommentIds;
                List<CommentVO> replyVOs = repliesMap.get(comment.getCommentId()).stream()
                        .map(reply -> convertToCommentVO(reply, userMap, likedCommentIdss))
                        .collect(Collectors.toList());
                vo.setReplies(replyVOs);
            } else {
                vo.setReplies(new ArrayList<>());
            }
            
            result.add(vo);
        }
        
        return result;
    }
    
    /**
     * 将评论对象转换为VO对象
     * @param comment 评论对象
     * @param userMap 用户映射
     * @param likedCommentIds 点赞的评论ID列表
     * @return VO对象
     */
    private CommentVO convertToCommentVO(Comment comment, Map<Long, User> userMap, List<Long> likedCommentIds) {
        CommentVO vo = new CommentVO();
        BeanUtils.copyProperties(comment, vo);
        
        // 设置用户信息
        User user = userMap.get(comment.getUserId());
        if (user != null) {
            vo.setNickname(user.getNickname() != null ? user.getNickname() : user.getUsername());
            vo.setAvatar(user.getAvatar().toString());
        }
        
        // 设置点赞状态
        vo.setUserLiked(likedCommentIds.contains(comment.getCommentId()));
        
        return vo;
    }
} 